<!--组件：批量授权用户-->
<template>
  <div>
    <a-button :disabled="disabled" @click="openDrawer">批量授权</a-button>

    <!-- 抽屉：授权 -->
    <a-drawer
      :visible="visible"
      title="批量授权"
      :width="360"
      @before-ok="authorizeRole"
      @cancel="closeDrawer"
    >
      <a-alert title="批量授权" style="margin-bottom: 20px">
        为选中的 {{ userIds.length }} 人进行角色授权
      </a-alert>

      <a-spin :loading="loading">
        <a-checkbox-group
          v-model:model-value="checkedKeys"
          direction="vertical"
        >
          <a-checkbox v-for="item in roleList" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-checkbox>
        </a-checkbox-group>
      </a-spin>
    </a-drawer>
  </div>
</template>

<script setup lang="ts" name="RoleBatchDrawer">
  import { PropType, ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { queryRoleRecordList } from '@/api/system/role';
  import { batchUpdateUserRole } from '@/api/system/permission';
  import { RoleRecord } from '@/api/system/model/roleModel';

  const props = defineProps({
    userIds: { type: Array as PropType<string[]>, default: () => [] },
    disabled: { type: Boolean, default: false },
  });

  const checkedKeys = ref<(string | number | boolean)[]>([]);

  const visible = ref<boolean>(false);
  const openDrawer = () => {
    getRoleList();
    visible.value = true;
  };
  const closeDrawer = () => {
    checkedKeys.value = [];
    visible.value = false;
  };

  const roleList = ref<RoleRecord[]>([]);
  const loading = ref<boolean>(false);
  const getRoleList = async () => {
    loading.value = true;
    try {
      const { data } = await queryRoleRecordList();
      roleList.value = data;
    } finally {
      loading.value = false;
    }
  };

  // func：保存授权信息
  const authorizeRole = async (done: (closed: boolean) => void) => {
    try {
      await batchUpdateUserRole({
        userIds: props.userIds,
        roleIds: checkedKeys.value as string[],
      });
      Message.success('修改成功');
    } finally {
      done(true);
      closeDrawer();
    }
  };
</script>
